package com.edvard.demo;


import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.os.SystemClock;
import android.util.Size;

import com.edvard.demo.customview.OverlayView;
import com.edvard.demo.env.Logger;

public class MainActivity extends CameraBaseActivity {

	private static final Logger LOGGER = new Logger();
	private static final Size DESIRED_PREVIEW_SIZE = new Size(640, 480);
	OverlayView previewOverlay;
	private Integer sensorOrientation;
	private Bitmap oriRGBBitmap = null;
	private boolean computingDetection = false;
	private Matrix oriRotate;
	private int overlayWidth;
	private int overlayHeight;

	@Override
	protected void onPreviewSizeChosen(Size size, int rotation) {

		// init classifier here

		previewWidth = size.getWidth();
		previewHeight = size.getHeight();

		sensorOrientation = rotation - getScreenOrientation();
		LOGGER.i("Camera orientation relative to screen canvas: %d", sensorOrientation);

		LOGGER.i("Initializing at size %dx%d - (width, height)", previewWidth, previewHeight);
		// horizon screen
		oriRGBBitmap = Bitmap.createBitmap(previewWidth, previewHeight, Bitmap.Config.ARGB_8888);

		// Because the camera preview bitmap here is mirror and horizon screen
		oriRotate = new Matrix();
		oriRotate.preScale(1.0f, -1.0f);
		oriRotate.postRotate(-90);

		previewOverlay = (OverlayView) findViewById(R.id.tracking_overlay);

		overlayWidth = previewOverlay.getWidth();
		float ratio = previewWidth / (float) previewHeight;
		overlayHeight = (int) (overlayWidth * ratio);


		previewOverlay.addCallback(
				new OverlayView.DrawCallback() {
					@Override
					public void drawCallback(final Canvas canvas) {
						// draw line, point, anything on image here
					}
				});
	}

	@Override
	protected void processImage() {
		previewOverlay.postInvalidate();

		// No mutex needed as this method is not ≤.
		if (computingDetection) {
			readyForNextImage();
			return;
		}
		computingDetection = true;

		oriRGBBitmap.setPixels(getRgbBytes(), 0, previewWidth, 0, 0, previewWidth, previewHeight);

		readyForNextImage();

		final Bitmap rotateBitmap = Bitmap.createBitmap(oriRGBBitmap, 0, 0, oriRGBBitmap.getWidth(), oriRGBBitmap.getHeight(), oriRotate, true);

		runInBackground(
				new Runnable() {
					@Override
					public void run() {
						final long startTime = SystemClock.uptimeMillis();

						double widthScale = overlayWidth / (float) rotateBitmap.getWidth();
						double heightScale = overlayHeight / (float) rotateBitmap.getHeight();

						previewOverlay.postInvalidate();
						computingDetection = false;
					}
				});
	}

	@Override
	protected Size getDesiredPreviewFrameSize() {
		return DESIRED_PREVIEW_SIZE;
	}

}
